<template>
  <div>
    <el-form ref="abiForm" :model="abiForm" :rules="rules" label-width="90px">
      <el-form-item :label="$t('contracts.contractName')" prop="contractName">
        <el-input v-model="abiForm.contractName" />
      </el-form-item>
      <el-form-item :label="$t('contracts.contractAddress')" prop="contractAddress">
        <el-input v-model="abiForm.contractAddress" />
      </el-form-item>
      <el-form-item :label="$t('contracts.contractAbi')" prop="contractAbi">
        <el-input v-model="abiForm.contractAbi" type="textarea" :autosize="{ minRows: 4}" />
      </el-form-item>
    </el-form>
    <div class="text-right send-btn">
      <el-button @click="close">{{ this.$t("text.cancel") }}</el-button>
      <el-button type="primary" :loading="loading" @click="submit('abiForm')">{{ this.$t("text.sure") }}</el-button>
    </div>
  </div>

</template>

<script>
import { importAbi, addFunctionAbi } from '@/api/exercises'
import { isJson } from '@/utils/util'
import web3 from '@/utils/ethAbi'
export default {
  name: 'ImportAbi',

  components: {
  },

  props: {
    address: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      abiContent: '',
      abiForm: {
        contractAbi: null,
        contractAddress: '',
        contractName: ''
      },
      loading: false
    }
  },

  computed: {
    rules() {
      const _this = this
      const validateJSON = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(_this.$t('rule.contractAbi')))
        } else {
          if (!isJson(value)) {
            callback(new Error(_this.$t('rule.correctJson')))
          } else {
            callback()
          }
        }
      }
      const data = {
        contractAbi: [
          {
            required: true,
            message: this.$t('rule.contractAbi'),
            trigger: 'blur'
          },
          {
            validator: validateJSON, trigger: 'blur'
          }
        ],
        contractAddress: [
          {
            required: true,
            message: this.$t('rule.contractAddress'),
            trigger: 'blur'
          }
        ],
        contractName: [
          {
            required: true,
            message: this.$t('rule.contractName'),
            trigger: 'blur'
          },
          {
            required: true,
            min: 1,
            max: 100,
            message: this.$t('rule.textLong1_100'),
            trigger: 'blur'
          }
        ]
      }
      return data
    }
  },

  watch: {
  },

  created() {
  },

  mounted() {
    if (this.address) {
      this.abiForm.contractAddress = this.address
    }
  },

  methods: {
    submit(abiForm) {
      this.$refs[abiForm].validate(valid => {
        if (valid) {
          this.queryImportAbi()
        } else {
          return false
        }
      })
    },
    queryImportAbi() {
      this.loading = true
      const data = {
        contractName: this.abiForm.contractName,
        contractAddress: this.abiForm.contractAddress,
        contractAbi: JSON.parse(this.abiForm.contractAbi),
        groupId: 1,
        account: localStorage.getItem('user')
      }
      importAbi(data)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.setMethod()
            this.$emit('importSuccess')
            this.$messageOnce({
              type: 'success',
              message: this.$t('system.importSuccess')
            })
          } else {
            this.$messageOnce({
              type: 'error',
              message: this.$chooseLang(res.code)
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$messageOnce({
            type: 'error',
            message: err.data || this.$t('text.systemError')
          })
        })
    },
    setMethod() {
      const Web3EthAbi = web3
      const arry = []
      if (this.abiForm.contractAbi) {
        const list = JSON.parse(this.abiForm.contractAbi)
        list.forEach(value => {
          if (value.name && value.type == 'function') {
            const data = {}
            let methodId
            if (localStorage.getItem('encryptionId') == 1) {
              methodId = Web3EthAbi.smEncodeFunctionSignature({
                name: value.name,
                type: value.type,
                inputs: value.inputs
              })
            } else {
              methodId = Web3EthAbi.encodeFunctionSignature({
                name: value.name,
                type: value.type,
                inputs: value.inputs
              })
            }
            data.methodId = methodId
            data.abiInfo = JSON.stringify(value)
            data.methodType = value.type
            arry.push(data)
          } else if (value.name && value.type == 'event') {
            const data = {}
            let methodId
            if (localStorage.getItem('encryptionId') == 1) {
              methodId = Web3EthAbi.smEncodeEventSignature({
                name: value.name,
                type: value.type,
                inputs: value.inputs
              })
            } else {
              methodId = Web3EthAbi.encodeEventSignature({
                name: value.name,
                type: value.type,
                inputs: value.inputs
              })
            }
            data.methodId = methodId
            data.abiInfo = JSON.stringify(value)
            data.methodType = value.type
            arry.push(data)
          }
        })
        if (arry.length) {
          this.addAbiMethod(arry)
        }
      }
    },
    addAbiMethod(list) {
      const data = {
        groupId: 1,
        methodList: list
      }
      addFunctionAbi(data).then(res => {
        if (res.code === 0) {
          console.log('method 保存成功！')
        } else {
          this.$messageOnce({
            message: this.$chooseLang(res.code),
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {
        this.$messageOnce({
          message: err.data || this.$t('text.systemError'),
          type: 'error',
          duration: 2000
        })
      })
    },
    close() {
      this.$emit('closeImport')
    }
  }
}
</script>

<style scoped>
</style>
